package com.ning.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
public class IndexController {

    @Autowired
    private DiscoveryClient discoveryClient;

    /**
     * 在使用hystrix-dashboard监控时，必须是监控@HystrixCommand注解相关的接口。
     * 和hystrix相关的接口
     *
     * @param str
     * @return
     */
    @HystrixCommand(fallbackMethod = "fallbackIndex")
    @PostMapping(value = "/index")
    public String index(String str) {
        System.out.println("A Service IndexController index str => " + str);
        return "A Service IndexController => " + str;
    }

    @GetMapping(value = "/discovery")
    public Object discovery() {
        List<String> services = discoveryClient.getServices();
        services.forEach(System.out::println);

        List<ServiceInstance> instances = discoveryClient.getInstances("springcloud-service-a");
        instances.forEach(s -> {
            System.out.println(s.getHost() + "\t");
            System.out.println(s.getPort() + "\t");
            System.out.println(s.getUri() + "\t");
        });
        return this.discoveryClient;
    }

    /**
     * 模拟请求超时
     *
     * @param str
     * @return
     */
    @PostMapping(value = "/timeout")
    public String timeout(String str) {
        try {
            TimeUnit.MINUTES.sleep(3);
        } catch (InterruptedException e) {
            System.out.println("timeout");
        }
        return "A Service Timeout Success";
    }

    public String fallbackIndex(String str) {
        return "A Service IndexController fallbackIndex => " + str;
    }

}
